"""
网络请求：发票解析
"""
import os
import requests
from src.config import settings
from src.models.user import User
from src.utils import compress_img


def query_inv_parse(filename: str):
    """请求登陆"""
    if not os.path.isfile(filename):
        return 1001, filename, u'无效的文件路径'
    user = User.get_user(require_login=True)
    if not user:
        return 1002, filename, u'未登录'
    try:
        if filename.endswith(('.png', '.jpeg', '.jpg', '.bmp')) and os.path.getsize(filename) > 1e6:
            file_bytes = compress_img(filename)
        else:
            with open(filename, 'rb') as fin:
                file_bytes = fin.read()
        response = requests.post(settings.inv_parse_url,
                                 files={'file': (os.path.basename(
                                     filename), file_bytes)},
                                 headers={'token': user.token}, timeout=10)
    except Exception as e:
        return 1003, filename, e
    if response.status_code != 200:
        return 1003, filename, f'网络请求出错，状态码：{response.status_code}'
    res = response.json()
    if res['code'] in [2000, 5002]:
        return 1000, filename, res['data']
    else:
        return 1004, filename, res['message']
